<!-- Set up a container element for the button -->
<div style="height: 1500px">
  <div id="paypal-button-container" class="mt-4"></div>
</div>
<script src="{{ asset('vendor/jquery/jquery-3.6.0.min.js') }}"></script>
<script src="{{ asset('vendor/layer/3.5.1/layer.js') }}"></script>
<!-- Include the PayPal JavaScript SDK -->
<script
  src="https://www.paypal.com/sdk/js?client-id={{ $payment_setting['key'] }}&currency={{ system_setting('base.currency') }}"></script>

<script>
  const token = "{{ csrf_token() }}";
  // Render the PayPal button into #paypal-button-container
  paypal.Buttons({
    // Call your server to set up the transaction
    createOrder: function (data, actions) {
      return fetch('/paypal_s/create', {
        method: 'POST',
        headers: {
          'X-CSRF-Token': token
        },
        body: JSON.stringify({
          orderNumber: "{{$order->number}}",
        })
      }).then(function (res) {
        return res.json();
      }).then(function (orderData) {
        if (orderData.error) {
          layer.alert(orderData.error.details[0].description, {
            title: '{{ __('common.text_hint') }}',
            closeBtn: 0,
            area: ['400px', 'auto'],
            btn: ['{{ __('common.confirm') }}']
          }, function (index) {
            window.location.reload();
            layer.close(index);
          });
        }
        return orderData.id;
      });
    },

    // Call your server to finalize the transaction
    onApprove: function (data, actions) {
      return fetch('/paypal_s/capture', {
        method: 'POST',
        headers: {
          'X-CSRF-Token': token
        },
        body: JSON.stringify({
          orderNumber: "{{$order->number}}",
          paypalOrderId: data.orderID,
          payment_gateway_id: $("#payapalId").val(),
        })
      }).then(function (res) {
        // console.log(res.json());
        return res.json();
      }).then(function (orderData) {
        // Successful capture! For demo purposes:
        console.log('Capture result', orderData, JSON.stringify(orderData, null, 2));
        let captureStatus = orderData.status
        if (captureStatus === 'COMPLETED') {
          layer.msg("Success");
        }
      });
    }
  }).render('#paypal-button-container');
</script>
